import {Component} from '@angular/core';

import {NavController, NavParams} from 'ionic-angular';
import { Http } from '@angular/http';

import {BookPage} from '../book/book';
import {parser} from '../../engine/findengine'

@Component({
  selector: 'page-category-list',
  templateUrl: 'category-list.html'
})
export class CategoryListPage {
  selectedItem: any;
  items: Array<{title: string, note: string, logo: string, url: string}>;
  page:number;

  constructor(public navCtrl: NavController, public navParams: NavParams,public http: Http,) {
    this.selectedItem = navParams.get('item');
    let url = this.selectedItem.url;
    this.page = 1;
    let url_1 = url.replace('@page',this.page.toString());
    this.items = [];
    http.get(url_1)
      .subscribe(data => {
        let books:Array<{name:string,logo:string,url:string}> ;
        books = JSON.parse(parser.tags_parse(data.url, data.text()));
        for (let i = 0; i < books.length; i++) {
          this.items.push({
            title: books[i].name,
            note: 'This is item #' + i,
            logo: books[i].logo,
            url: books[i].url
          });
        }
      }, error => {
        console.log(JSON.stringify(error.json()));
      });// end http.get
  } // end constructor

  itemTapped(event, item) {
    this.navCtrl.push(BookPage, {
      item: item
    });
  }

  doInfinite(infiniteScroll) {
    this.page += 1;
    let url = this.selectedItem.url;
    let url_1 = url.replace('@page',this.page.toString());
    this.http.get(url_1)
      .subscribe(data => {
        let books:Array<{name:string,logo:string,url:string}> ;
        books = JSON.parse(parser.tags_parse(data.url, data.text()));
        for (let i = 0; i < books.length; i++) {
          this.items.push({
            title: books[i].name,
            note: 'This is item #' + i,
            logo: books[i].logo,
            url: books[i].url
          });
        }
        infiniteScroll.complete();
      }, error => {
        console.log(JSON.stringify(error.json()));
      });// end http.get
  }
}
